//
//  PlaySongListViewController.m
//  Mecca
//
//  Created by TH-MAC02 on 7/28/14.
//  Copyright (c) 2014 TapDash Heuristics. All rights reserved.
//
#import "PlaySongListViewController.h"
#import "LocalPlayerClass.h"
#import "ParserClass.h"
#import "DownloadedSongs.h"
#import "AudioPlayManager.h"
#import <AVFoundation/AVFoundation.h>
#import <FacebookSDK/FacebookSDK.h>


@interface PlaySongListViewController (){
    int idxSong;
    NSString *value;
    
    NSString *dur;
    
    float start;
    
    int x;
    int c;
    int z;
    
    
    BOOL isShuffle;
    NSString *isRepeat;
    
    NSTimer *timer;
    
}
@end
@implementation PlaySongListViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    // [[AudioPlayManager shareObject] setAudioURL:[[ParserClass sharedItems] urlSong] playImmediately:YES isLocal:[[NSURL URLWithString:[[ParserClass sharedItems] urlSong]] isFileURL]];
    
    //    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    //    [defaultCenter addObserver:self selector:@selector(handleProgressUpdate) name:AudioPlayManagerProgressUpdated object:nil];
    
    [self.viewLyrics setFrame:CGRectMake(self.viewLyrics.frame.origin.x, self.viewLyrics.frame.origin.y, self.viewLyrics.frame.size.width, self.viewLyrics.frame.size.height)];
    
    DownloadedSongs *downloadedSongs = [[ParserClass sharedItems] downloadedSongs][0];
    
    [self setImageString:[downloadedSongs songImg]];
    [self songs:idxSong];
    
    //    NSTimer * updateTimer = [NSTimer scheduledTimerWithTimeInterval:.01 target:self selector:@selector(updateCurrentTime) userInfo:self.audioPlayer repeats:YES];
    //
    //    [updateTimer fire];
    
    LocalPlayerClass *lp = [LocalPlayerClass sharedItems];
    
    timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateCurrentTime) userInfo:nil repeats:YES];
    self.songSlider.maximumValue = lp.audioPlayer.duration;
    
    [self.songSlider addTarget:self action:@selector(progressSliderMoved:) forControlEvents:UIControlEventValueChanged];
    
    
    x = idxSong; // default
    c = x + 1; // next
    if(x == 0){
        z = [[[ParserClass sharedItems] downloadedSongs] count];
        //last count nung array mo
    }else{
        z = x - 1;
    }
    
    value = @"Play";
    isShuffle = NO;
    isRepeat = @"No";
    
    NSLog(@"shuffle = %hhd", isShuffle);
    
    
    [_lblStart start];
    
    
    NSLog(@"Duration Click %@", dur);
    
    
    
}
- (void)songs:(NSInteger)index{
    
    LocalPlayerClass *lp = [LocalPlayerClass sharedItems];
    
    
    
    DownloadedSongs *downloadedSongs = [[ParserClass sharedItems] downloadedSongs][index];
    
    //[[LocalPlayerClass sharedItems] playAudioFromData:[downloadedSongs songData]] ;
    
    //NSError *error = nil;
    
    //<<<<<<< .mine
    //    [lp playAudioFromData:[downloadedSongs songData]];
    //=======
    dur = [downloadedSongs durations];
    //>>>>>>> .r191
    
    
    [self playAudioFromData:[downloadedSongs songData]];
    // NSError *error;
    
    //  [[LocalPlayerClass sharedItems] playAudioFromData:[downloadedSongs songData]];
    
    
    NSData *data = [NSData dataWithData:[downloadedSongs songData]];
    
    NSString *yourstring = [[NSString alloc] initWithData:data encoding:NSUTF16StringEncoding]; // Or any other encoding method
    
    NSURL *url = [NSURL URLWithString:yourstring];
    
    //    self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
    //    self.audioPlayer.delegate = self;
    //    [self.audioPlayer prepareToPlay];
    //    [self.audioPlayer play];
    
    [self setImageString:[downloadedSongs songImg]];
    
    self.endSongLbl.text = [downloadedSongs durations];
    
    self.nowPlayingLbl.text = [downloadedSongs songName];
    
    self.lblSongName.text = [downloadedSongs songName];
    
    self.lblArtistName.text = [downloadedSongs artistname];
    
    
    if ([[downloadedSongs songLyrics] isEqualToString:@""]) {
        
        self.lblNotAvail.hidden = NO;
        self.txtFLyrics.hidden = YES;
        self.lblNotAvail.text = @"Lyrics not Available";
        
        
    }else{
        self.lblNotAvail.hidden = YES;
        self.txtFLyrics.hidden = NO;
        self.txtFLyrics.text = [downloadedSongs songLyrics];
        
    }
    
    
    NSLog(@"Data image =  %@", [downloadedSongs songImg]);
    
    
    
    //<<<<<<< .mine
    
    //
    //=======
    //    //[self.songSlider setMaximumValue:lp.audioPlayer.currentTime];
    //
    //>>>>>>> .r241
    NSLog(@"yourstring = %@", url);
    //<<<<<<< .mine
    
    // Duration Timer Start
    
    [_lblStart start];
    
    
    //=======
    
    
    //>>>>>>> .r191
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)getPlaySongIndex:(int)idx{
    
    NSLog(@"Get Play Song idx = %i", idx);
    idxSong = idx;
}
-(void)setImageString:(NSString *)strImage{
    
    NSString *strImg = [NSString stringWithFormat:@"http://192.185.93.102/~boomeran/backend-panel/%@",strImage];
    
    [NSThread detachNewThreadSelector:@selector(showImage:) toTarget:self withObject:strImg];
    
}
-(void)showImage:(NSString*)imageShow{
    @autoreleasepool {
        NSData *imageList = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageShow]];
        [self.albumImg setAlpha:0];
        [UIView animateWithDuration:0.5 animations:^{
            
            self.albumImg.image = [UIImage imageWithData:imageList];
            [self.activityIn setHidden:YES];
            [self.albumImg setAlpha:1];
        } completion:^(BOOL finished) {
            
        }];
        
        
        //[self animationActivity];
    }
}
- (IBAction)backAction:(id)sender {
    
    //     [[LocalPlayerClass sharedItems] stopAudio];
    [self.navigationController popViewControllerAnimated:YES];
    
    
    //    [self dismissViewControllerAnimated:YES completion:nil];
}
- (IBAction)playPauseAction:(id)sender {
    
    LocalPlayerClass *lp = [LocalPlayerClass sharedItems];
    
    NSLog(@"asdasd");
    
    if ([value isEqualToString:@"Play"]) {
        
        value = @"Pause";
        
        [self.playPauseBtn setImage:[UIImage imageNamed:@"play_player.png"] forState:UIControlStateNormal];
        
        // [[LocalPlayerClass sharedItems].audioPlayer pause];
        
        //[_lblStart pause];
        
        [lp.audioPlayer pause];
        //<<<<<<< .mine
        
        //=======
        //  [_lblStart pause];
        
        //>>>>>>> .r191
    }else if ([value isEqualToString:@"Pause"]){
        
        value = @"Play";
        
        [self.playPauseBtn setImage:[UIImage imageNamed:@"pause.png"] forState:UIControlStateNormal];
        
        //[[LocalPlayerClass sharedItems].audioPlayer play];
        
        [lp.audioPlayer play];
        //<<<<<<< .mine
        
        [_lblStart start];
        //=======
        //  [_lblStart start];
        //>>>>>>> .r191
    }
    
    
}
- (IBAction)nextAction:(id)sender {
    
    if(x == ([[[ParserClass sharedItems] downloadedSongs] count] - 1)){ /// kapag siya na ung pinaka last na slider mo
        
        x = 0;
        
        NSLog(@"value last = %@", [[[ParserClass sharedItems] downloadedSongs] objectAtIndex:x]);
        //<<<<<<< .mine
        
        [self.playPauseBtn setImage:[UIImage imageNamed:@"pause.png"] forState:UIControlStateNormal];
        
        [_lblStart reset];
        
        //=======
        //       [_lblStart reset];
        //>>>>>>> .r191
        [self songs:x];
        
    }else{
        
        x = x + 1; /// Declare mo ung next slider
        
        NSLog(@"value next = %@", [[[ParserClass sharedItems] downloadedSongs] objectAtIndex:x]);
        [_lblStart reset];
        [self.playPauseBtn setImage:[UIImage imageNamed:@"pause.png"] forState:UIControlStateNormal];
        \
        [_lblStart reset];
        
        [self songs:x];
        
    }
    //<<<<<<< .mine
    //
    //=======
    //
    //>>>>>>> .r191
}
- (IBAction)previousAction:(id)sender {
    
    if(x == 0){ // kapag pinaka 1st slider siya
        x = [[[ParserClass sharedItems] downloadedSongs] count] - 1; // Declare new value for x
        NSLog(@"value last = %@", [[[ParserClass sharedItems] downloadedSongs] objectAtIndex:x]);
        [_lblStart reset];
        [self.playPauseBtn setImage:[UIImage imageNamed:@"pause.png"] forState:UIControlStateNormal];
        
        [_lblStart reset];
        [self songs:x];
        
    }else{
        x = x - 1; // Declare new value for x
        NSLog(@"value next = %@", [[[ParserClass sharedItems] downloadedSongs] objectAtIndex:x]);
        [_lblStart reset];
        [self.playPauseBtn setImage:[UIImage imageNamed:@"pause.png"] forState:UIControlStateNormal];
        
        [_lblStart reset];
        [self songs:x];
        
    }
    
}
- (void) playAudioFromData: (NSData*) data {
    NSError *error = nil;
    
    //    player=[[AVAudioPlayer alloc]initWithContentsOfURL:url error:NULL];
    //    player.delegate=self;
    //    [player play];
    
    LocalPlayerClass *lp = [LocalPlayerClass sharedItems];
    
    [lp stopAudio];
    lp.audioPlayer = [[AVAudioPlayer alloc] initWithData:data error:&error];
    lp.audioPlayer.delegate = self;
    [lp.audioPlayer prepareToPlay];
    [lp.audioPlayer play];
    
}
-(void)stopAudio{
    
    LocalPlayerClass *lp = [LocalPlayerClass sharedItems];
    
    if(lp.audioPlayer && [lp.audioPlayer isPlaying]){
        [lp.audioPlayer stop];
        lp.audioPlayer=nil;
    }
    
}
#pragma mark - Audio Delegate
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
    
    LocalPlayerClass *lp = [LocalPlayerClass sharedItems];
    
    NSLog(@"Finish Playing");
    
    //    if ([_lblStart.text isEqualToString:dur]) {
    //
    //        NSLog(@"Music Done %@ %@", self.lblStart.text,dur);
    //
    //    }
    
    NSLog(@"shuffle = %hhd", isShuffle);
    
    if ([isRepeat isEqualToString:@"No"]) {
        
        if (isShuffle == 0) {
            
            NSLog(@"Not Shuffle");
            
            if(x == ([[[ParserClass sharedItems] downloadedSongs] count] - 1)){ /// kapag siya na ung pinaka last na slider mo
                
                //                x = 0;
                //
                //                NSLog(@"value last = %@", [[[ParserClass sharedItems] downloadedSongs] objectAtIndex:x]);
                //                [_lblStart reset];
                //                [_lblStart reset];
                //
                //                [self songs:x];
                
                [lp.audioPlayer stop];
                
            }else{
                
                x = x + 1; /// Declare mo ung next slider
                
                NSLog(@"value next = %@", [[[ParserClass sharedItems] downloadedSongs] objectAtIndex:x]);
                [_lblStart reset];
                [_lblStart reset];
                
                [self songs:x];
                
            }
            
        }else if (isShuffle == 1){
            
            NSLog(@"Shuffle");
            
            NSUInteger randomIndex = arc4random() % [[[ParserClass sharedItems] downloadedSongs] count];
            [self songs:randomIndex];
            
        }
        
    }else if([isRepeat isEqualToString:@"Repeat One"]){
        [self songs:x];
        
    }else if ([isRepeat isEqualToString:@"Repeat All"]){
        
        if(x == ([[[ParserClass sharedItems] downloadedSongs] count] - 1)){ /// kapag siya na ung pinaka last na slider mo
            
            x = 0;
            
            NSLog(@"value last = %@", [[[ParserClass sharedItems] downloadedSongs] objectAtIndex:x]);
            [_lblStart reset];
            [_lblStart reset];
            
            [self songs:x];
            
        }else{
            
            x = x + 1; /// Declare mo ung next slider
            
            NSLog(@"value next = %@", [[[ParserClass sharedItems] downloadedSongs] objectAtIndex:x]);
            [_lblStart reset];
            [_lblStart reset];
            
            [self songs:x];
            
        }
    }
    
    
    
}
- (IBAction)repeatAction:(id)sender{
    
    NSLog(@"Repeat");
    
    if ([isRepeat isEqualToString:@"No"]) {
        isRepeat = @"Repeat One";
        
        [self.repeatBtn setImage:[UIImage imageNamed:@"repeatWhite.png"] forState:UIControlStateNormal];
        NSLog(@"repeat = %@", isRepeat);
    }else if ([isRepeat isEqualToString:@"Repeat One"]){
        isRepeat = @"Repeat All";
        [self.repeatBtn setImage:[UIImage imageNamed:@"repeatWhite.png"] forState:UIControlStateNormal];
        NSLog(@"repeat = %@", isRepeat);
    }else if ([isRepeat isEqualToString:@"Repeat All"]){
        isRepeat = @"No";
        [self.repeatBtn setImage:[UIImage imageNamed:@"repeat.png"] forState:UIControlStateNormal];
        NSLog(@"repeat = %@", isRepeat);
    }
}
- (IBAction)shuffleAction:(id)sender{
    
    NSLog(@"Shuffle");
    
    if (isShuffle == 0) {
        isShuffle = YES;
        [self.shuffleBtn setImage:[UIImage imageNamed:@"shuffleWhite.png"] forState:UIControlStateNormal];
        NSLog(@"shuffle = %hhd", isShuffle);
    }else if (isShuffle == 1){
        isShuffle = NO;
        [self.shuffleBtn setImage:[UIImage imageNamed:@"shuffle.png"] forState:UIControlStateNormal];
        NSLog(@"shuffle = %hhd", isShuffle);
    }
    
    
    
    
}
#pragma mark Slider Methods;
-(void) handleProgressUpdate
{
    start = [[AudioPlayManager shareObject] currentPlayedProgress];
    self.songSlider.value = [[AudioPlayManager shareObject] currentPlayedProgress];
    AudioPlayManager *ad = [AudioPlayManager shareObject];
    //    float startPrev = self.processSlider.value;
    //    int intValue = (int) floor(startPrev);
    //
    //    NSString* formattedNumber = [NSString stringWithFormat:@"%.02f", self.processSlider.value];
    NSLog(@"processslider = %d", ad.audioController.stream.currentTimePlayed.second);
    //[self.lblPrevStart setText:[NSString stringWithFormat:@"0:0%d",ad.audioController.stream.currentTimePlayed.second]];
    if (ad.audioController.stream.currentTimePlayed.second >= 10) {
        //[self.lblStart setText:[NSString stringWithFormat:@"0:%d",ad.audioController.stream.currentTimePlayed.second]];
    }
    //
    //    if (self.songSlider.value == 1) {
    //        [[AudioPlayManager shareObject] stop];
    //    }
}
//-(void)sliderMove{
//
//    float f = [[NSString stringWithFormat:@"%@",_lblStart.text] floatValue];
//
//
//    [self.songSlider setValue:f];
//
//}
- (IBAction)processSliderValueChanged:(id)sender {
    //    CGFloat duration = [AudioPlayManager shareObject].duration;
    //    unsigned int currentTimeInsecond = duration * [_songSlider value];
    //    [[AudioPlayManager shareObject] seekToMinutes:currentTimeInsecond/60 Seconds:currentTimeInsecond%60];
    //
    //    NSLog(@"current time = %i", currentTimeInsecond);
    
    // Set the label text to the value of the slider as it changes
    //    self.startSongLbl.text = [NSString stringWithFormat:@"%f", self.songSlider.value];
    
    NSLog(@"Moved");
}
- (void)updateCurrentTime
{
    
    LocalPlayerClass *lp = [LocalPlayerClass sharedItems];
    
    self.startSongLbl.text = [NSString stringWithFormat:@"%d:%02d", (int)lp.audioPlayer.currentTime / 60, (int)lp.audioPlayer.currentTime % 60, nil];
    
    //    self.endSongLbl.text = [NSString stringWithFormat:@"%d:%02d", ((int)self.audioPlayer.duration / 60) - ((int)self.audioPlayer.currentTime / 60), ((int)self.audioPlayer.duration % 60) - ((int)self.audioPlayer.currentTime % 60), nil];
    self.songSlider.value = lp.audioPlayer.currentTime;
    
    NSLog(@"lp currentTime = %f", self.songSlider.value);
}
- (IBAction)progressSliderMoved:(UISlider *)sender
{
    LocalPlayerClass *lp = [LocalPlayerClass sharedItems];
    
    
    [lp.audioPlayer stop];
    [lp.audioPlayer setCurrentTime:self.songSlider.value];
    [lp.audioPlayer prepareToPlay];
    [lp.audioPlayer play];
}
- (IBAction)btnShowLyrics:(id)sender {
    
    NSLog(@"Show Lyrics");
    [UIView animateWithDuration:0.5 animations:^{
        
        [self.viewLyrics setFrame:CGRectMake(self.viewLyrics.frame.origin.x, 289, self.viewLyrics.frame.size.width, self.viewLyrics.frame.size.height)];
        
    } completion:^(BOOL finished) {
        
        self.btnShowProp.hidden = YES;
        
    }];
    
    
    
    
}
- (IBAction)btnHideLyrics:(id)sender {
    
    
    NSLog(@"Hide Lyrics");
    
    [UIView animateWithDuration:0.5 animations:^{
        
        [self.viewLyrics setFrame:CGRectMake(self.viewLyrics.frame.origin.x, 538, self.viewLyrics.frame.size.width, self.viewLyrics.frame.size.height)];
        
    } completion:^(BOOL finished) {
        
        self.btnShowProp.hidden = NO;
        
    }];
    
}




- (IBAction)sliderTouchDown:(id)sender {
    
    [[AudioPlayManager shareObject] pause];
    
}
- (IBAction)sliderTouchInside:(id)sender {
    
    [[AudioPlayManager shareObject] resume];
    
}
- (IBAction)sliderTouchUpOutside:(id)sender {
    
    [[AudioPlayManager shareObject] resume];
    
}


#pragma mark - OG;


- (IBAction)shared:(id)sender {
    
    [FBSettings setDefaultDisplayName:[[FBSettings defaultDisplayName] precomposedStringWithCanonicalMapping]];
    
    id<FBOpenGraphAction> action = (id<FBOpenGraphAction>)[FBGraphObject graphObject];
    [action setObject:@"https://example.com/book/Snow-Crash.html" forKey:@"book"];
    
    [FBDialogs presentShareDialogWithOpenGraphAction:action
                                          actionType:@"books.reads"
                                 previewPropertyName:@"book"
                                             handler:^(FBAppCall *call, NSDictionary *results, NSError *error) {
                                                 if(error) {
                                                     NSLog(@"Error: %@", error.description);
                                                 } else {
                                                     NSLog(@"Success!");
                                                 }
                                             }];
    
}


@end